package com.uxsino.simo.indicator.retractor;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.uxsino.commons.utils.config.ConfigProp;
import com.uxsino.simo.networkentity.EntityInfo;
import com.uxsino.simo.query.QueryContext;
import com.uxsino.simo.query.QueryTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class DatasetListRetractor extends ListValueRetractor {
    private static Logger logger = LoggerFactory.getLogger(DatasetListRetractor.class);

    @ConfigProp(name = "recordset_num")
    private int datasetIndex = 1; // starts from 1, first data set by default

    @Override
    public Object doRetract(EntityInfo entity, QueryContext ctxt, QueryTemplate qt, Object obj) {
        ArrayList<Map<String, Object>> records = new ArrayList<Map<String, Object>>();
        if (null == obj)
            return records;
        ObjectMapper mapper = new ObjectMapper();
        MultiDataset md = mapper.convertValue(obj, new TypeReference<MultiDataset>(){});
        // Dataset nr = (Dataset) obj;
        if (md.size() < datasetIndex) {
            logger.error("recordset {} is required but onle {} recordset is returned", datasetIndex, md.size());
            return null;
        }

        Dataset nr = md.get(datasetIndex - 1);

        for (String[] row : nr.records) {
            HashMap<String, Object> fieldValues = new HashMap<String, Object>();
            for (ColumnEntry entry : columnEntries) {
                Object value = null;

                // <cloumn col_id="1" field="fieldName">
                int col_num;

                if (nr.columnNames.containsKey(entry.index)) {
                    col_num = nr.columnNames.get(entry.index);
                } else {
                    try {
                        col_num = Integer.parseInt(entry.index.trim());
                    } catch (NumberFormatException e) {
                        logger.debug("col_id: " + entry.index + " not found");
                        continue;
                    }
                }
                if (col_num < 1 || col_num > row.length) {
                    logger.debug("column index out of range: " + entry.index);
                    continue;
                }
                String s = row[col_num - 1];
                if (s != null) {
                    value = entry.retractor.retract(entity, ctxt, qt, s);
                    fieldValues.put(entry.field.getName(), value);
                } else {
                    logger.debug("column index out of range:{} . value is null!", entry.index);
                }

            }
            records.add(fieldValues);

        }
        return records;

    }

}
